//
//  EmoticonAttachment.swift
//  01-表情键盘
//
//  Created by Apple on 15/9/30.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class EmoticonAttachment: NSTextAttachment {

    /// 表情的字符串
    var chs: String?
    
    /// 生成带表情图片的属性文本
    class func emotionText(emoticon: Emoticon, font: UIFont) -> NSAttributedString {
        
        let attachment = EmoticonAttachment()
        
        // 记录表情符号字符串
        attachment.chs = emoticon.chs
        
        attachment.image = UIImage(contentsOfFile: emoticon.imagePath)
        
        // 获取字体高度 bounds 的 x/y 是 contentOffset
        // 视图的 frame = bounds * transform
        let h = font.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: h, height: h)
        
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        
        // 设置字体属性 － 所有富文本的属性，在UIKit框架的第一个.h中！
        imageText.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: 1))
        
        return imageText
    }
}
